<?php
// 应用公共文件

/**
 * 生成随机不重复的六位数
 */

use think\facade\Db;

if (!function_exists('InviteCode')) {
    function InviteCode()
    {
        $v0 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $v1 = $v0[rand(0, 25)] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        for ($v2 = md5($v1, !0), $v3 = '0123456789ABCDEFGHIJKLMNOPQRSTUV', $v4 = '', $v5 = 0; $v5 < 6; $v6 = ord($v2[$v5]), $v4 .= $v3[($v6 ^ ord($v2[$v5 + 6])) - $v6 & 31], $v5++) {
        }
        return $v4;
    }
}


if (!function_exists('createdGoodsSn')) {
    function createdGoodsSn()
    {
        return '6' . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))) . str_pad(mt_rand(1, 9999999), 7, '0', STR_PAD_LEFT), 0, 11);
    }
}


/**
 * @param $arr
 * @return mixed
 */
if (!function_exists('WhereDel')) {
    function WhereDel($arr, $alias = 'a.')
    {
        $new_arr = [];
        foreach ($arr as $key => &$v) {
            if ($v === '' || $v === null) {
                unset($arr[$key]);
            } else {
                $new_arr[$alias . $key] = $v;
            }
        }
        return $new_arr;
    }
}


/**
 * Redis原子锁
 * @param $key
 * @param int $va
 */
if (!function_exists('RedisLock')) {
    function RedisLock($key, $va = 3, $msg = '请求过于频繁')
    {
        $redis = \think\facade\Cache::store('redis');
        $check = $redis->exists($key);
        if ($check) {
            $redis->incr($key);
            $count = $redis->get($key);
            if ($count >= 10) {
                $redis->del($key);
            } else {
                if ($count > 1) {
                    $result = [
                        'code' => 500,
                        'msg' => '请求过于频繁',
                        'data' => (object)[],
                    ];
                    header('Content-Type:application/json; charset=utf-8');
                    echo json_encode($result);
                    die;
                }
            }

        } else {
            $redis->incr($key);
            $redis->expire($key, $va);
        }
    }
}


/**
 * 获取时间
 * @return array
 */
if (!function_exists('DateTime')) {
    function DateTime()
    {
        $arr['t_s'] = date('Y-m-d', time()) . ' 00:00:00';
        $arr['t_e'] = date('Y-m-d', time()) . ' 23:59:59';
        $arr['y_s'] = date('Y-m-d H:i:s', strtotime('-1 day 00:00:00'));
        $arr['y_e'] = date('Y-m-d H:i:s', strtotime('-1 day 23:59:59'));
        $w_s = mktime(0, 0, 0, date('m'), date('d') - date('w') + 1, date('Y'));
        $arr['w_s'] = date('Ymd', $w_s);
        $arr['w_s_1'] = $w_s;
        $w_e = mktime(23, 59, 59, date('m'), date('d') - date('w') + 7, date('Y'));
        $arr['w_e'] = date('Ymd', $w_e);
        $arr['w_e_1'] = $w_e;
        return $arr;
    }
}

/**
 * 图片地址替换
 */
if (!function_exists('imageSrcReplace')) {
    function imageSrcReplace($str)
    {
        $pattern = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png|\.jpeg]))[\'|\"].*?[\/]?>/i";
        $content = preg_replace_callback($pattern, function ($ma) {
            $src = env('qiniu.domain') . $ma[1];
            return str_replace($ma[1], $src, $ma[0]);
        }, $str);
        return $content;
    }
}

function CurlPost($url, $data = array())
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;

}

if (!function_exists('CurlJson')) {
    function CurlJson($url, $params)
    {
        $data = json_encode($params);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Content-Length:' . strlen($data)]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
}


function CurlGet($url)
{
    $header = array(
        'Accept: application/json',
    );
    $curl = curl_init();
    //设置抓取的url
    curl_setopt($curl, CURLOPT_URL, $url);
    //设置头文件的信息作为数据流输出
    curl_setopt($curl, CURLOPT_HEADER, 0);
    // 超时设置,以秒为单位
    curl_setopt($curl, CURLOPT_TIMEOUT, 1);
    // 超时设置，以毫秒为单位
    // curl_setopt($curl, CURLOPT_TIMEOUT_MS, 500);

    // 设置请求头
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    //设置获取的信息以文件流的形式返回，而不是直接输出。
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    //执行命令
    $data = curl_exec($curl);
    // 显示错误信息
    if (curl_error($curl)) {
    } else {
        // 打印返回的内容
        curl_close($curl);
        return $data;
    }
}

/**
 * 解析emoji表情
 */
if (!function_exists('get_emoji')) {
    function get_emoji($content)
    {
        $return = preg_replace_callback('/@E(.{6}==)/', function ($r) {
            return base64_decode($r[1]);
        }, $content);
        return $return;
    }
}


if (!function_exists('cryption')) {
    function cryption($string, $operation, $key = '')
    {
        $key = md5($key);
        $key_length = strlen($key);
        $string = $operation == 'D' ? base64_decode($string) : substr(md5($string . $key), 0, 8) . $string;
        $string_length = strlen($string);
        $rndkey = $box = array();
        $result = '';
        for ($i = 0; $i <= 255; $i++) {
            $rndkey[$i] = ord($key[$i % $key_length]);
            $box[$i] = $i;
        }
        for ($j = $i = 0; $i < 256; $i++) {
            $j = ($j + $box[$i] + $rndkey[$i]) % 256;
            $tmp = $box[$i];
            $box[$i] = $box[$j];
            $box[$j] = $tmp;
        }
        for ($a = $j = $i = 0; $i < $string_length; $i++) {
            $a = ($a + 1) % 256;
            $j = ($j + $box[$a]) % 256;
            $tmp = $box[$a];
            $box[$a] = $box[$j];
            $box[$j] = $tmp;
            $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
        }
        if ($operation == 'D') {
            if (substr($result, 0, 8) == substr(md5(substr($result, 8) . $key), 0, 8)) {
                return substr($result, 8);
            } else {
                return '';
            }
        } else {
            return str_replace('=', '', base64_encode($result));
        }
    }
}

/**
 * 客户端ip
 */
if (!function_exists('getClientIp')) {
    function getClientIp($type = 0)
    {
        $type = $type ? 1 : 0;
        static $ip = NULL;
        if ($ip !== NULL) return $ip[$type];
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos) unset($arr[$pos]);
            $ip = trim($arr[0]);
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $long = sprintf("%u", ip2long($ip));
        $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }
}


if (!function_exists('tree')) {
    function tree($list, $code = 'id', $parent_code = 'pid', $son = 'child', $parent_root = 0)
    {
        $tree = array();
        if (is_array($list)) {
            $refer = array();
            foreach ($list as $key => $data) {
                $refer[$data[$code]] =& $list[$key];
            }
            foreach ($list as $key => $data) {
                $parentId = $data[$parent_code];
                if ($parent_root == $parentId) {
                    $tree[] =& $list[$key];
                } else {
                    if (isset($refer[$parentId])) {
                        $parent =& $refer[$parentId];
                        $parent[$son][] =& $list[$key];
                    }
                }
            }
        }
        return $tree;
    }

}

function createdOrderSn()
{
    return date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
}


if (!function_exists('checkPhoneNumber')) {
    function checkPhoneNumber($phone_number)
    {
        //中国联通号码：130、131、132、145（无线上网卡）、155、156、185、186、176、175,166,146
        //中国移动号码：134、135、136、137、138、139、147（无线上网卡）、148、150、151、152、157、158、159、178、182、183、184、187、188、198
        //中国电信号码：133、153、180、181、189、177、173、149、199
        //14/16/19号段
        $g = "/^1[3456789]\d{9}$/";
        $g2 = "/^19[89]\d{8}$/";
        $g3 = "/^166\d{8}$/";
        if (preg_match($g, $phone_number)) {
            return true;
        } else if (preg_match($g2, $phone_number)) {
            return true;
        } else if (preg_match($g3, $phone_number)) {
            return true;
        }
        return false;
    }
}

/**
 * 计算中奖概率
 * @param $proArr
 * @return int|string
 */
if (!function_exists('getRand')) {
    function getRand($proArr)
    {
        $rs = '';
        $proSum = array_sum($proArr);
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $rs = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset($proArr);
        return $rs;
    }
}

//系统配置
if (!function_exists('system_config')) {
    function SystemConfig($name)
    {
        $redis = \think\facade\Cache::store('redis');
        $value = $redis->get('config');
        if ($value == NULL) {
            $v = Db::name('system_config')->select()->toArray();
            $v = array_column($v, NULL, 'name');
            $redis->set('config', json_encode($v));
            $value = $redis->get('config');
        }
        $value = json_decode($value, true);
        return $value[$name]['value'];
    }
}


/**
 * 获取系统配置
 */
if (!function_exists('get_config')) {
    function get_config(int $type = 1, $name = 'default')
    {
        $key = md5("system_configs:{$type}");
        if (($result = \cache($key)) === false || empty($result)) {
            $result = \think\facade\Db::name('configs')->where('type', $type)->column('value', 'name');
            if (empty($result)) return null;
            \cache($key, $result);
        }
        if ($name != 'default') {
            if (!isset($result[$name])) return null;
            if (!is_null(json_decode($result[$name], true)))
                $result = json_decode($result[$name], true);
            else
                $result = $result[$name];
        } else {
            foreach ($result as $key => $value) {
                if (!is_null(json_decode($result[$key], true)))
                    $result[$key] = json_decode($result[$key], true);
            }
        }
        return $result;
    }
}

/**
 * 对象转数组
 */
if (!function_exists('object_array')) {
    function object_array($array)
    {
        if (is_object($array)) {
            $array = (array)$array;
        }
        if (is_array($array)) {
            foreach ($array as $key => $value) {
                $array[$key] = object_array($value);
            }
        }
        return $array;
    }
}


/**
 * 安全密码验证
 */
if (!function_exists('security_password_verify')) {
    function security_password_verify($param)
    {
        header('Content-Type:application/json; charset=utf-8');
        $pay_pass = isset($param->data['pay_pass']) ? $param->data['pay_pass'] : ''; // 支付密码
        if (empty($pay_pass)) {
            echo json_encode(['msg' => '交易密码为空', 'code' => 500, 'data' => null]);
            exit;
        }
        $user = $param->user;
        if (empty($user->paypass)) {
            echo json_encode(['msg' => '你还未设置交易密码', 'code' => 603, 'data' => null]);
            exit;
        }
        if ($user->is_pay_pass > 4) {
            echo json_encode(['msg' => '账户已锁定，请修改交易密码', 'code' => 604, 'data' => null]);
            exit;
        }
        if (sha1($pay_pass) != $user->paypass) {
            \think\facade\Db::name('user')->where(['id' => $param->uid])->inc('is_pay_pass')->update();
            $surplus = 5 - $user->is_pay_pass - 1;
            if ($surplus < 1) {
                echo json_encode(['msg' => '账户已锁定，请修改交易密码', 'code' => 604, 'data' => null]);
                exit;
            } else {
                echo json_encode(['msg' => '交易密码错误，剩余' . $surplus . '次', 'code' => 500, 'data' => null]);
                exit;
            }
        }
    }
}


/**
 * 二维数组根据某个字段排序
 * @param array $array 要排序的数组
 * @param string $key 要排序的键
 * @param string $sort 排序类型 SORT_ASC SORT_DESC
 * return array 排序后的数组
 */
function arraySort($array, $key, $sort = SORT_ASC)
{
    $keysValue = array();
    foreach ($array as $k => $v) {
        $keysValue[$k] = $v[$key];
    }
    array_multisort($keysValue, $sort, $array);
    return $array;
}